import { useEffect, useRef, useState } from "react";
import { PickerView, PickerViewColumn, View } from "@tarojs/components";
import { add } from "lodash-es";

import dayjs from "dayjs";
import toObject from "dayjs/plugin/toObject"; // ES 2015
import { useReactive } from "ahooks";

dayjs.extend(toObject);

const current = dayjs();

const findIndex = (list: any[], target) => list.findIndex((e) => e === target);
const generateList = (length: number, startValue = 0) =>
  new Array(length).fill(startValue).map(add) as number[];

const getdayList = (date) => {
  const days = dayjs(date).daysInMonth();
  return generateList(days, 1);
};

const monthList: number[] = generateList(12);
const yearList: number[] = generateList(
  31,
  current.subtract(15, "year").get("year")
);

type PopupDateProps = {
  value: string;
};

type PopupDateEvents = {
  onChange: (e: string) => void;
};

export default ({ value, onChange }: PopupDateProps & PopupDateEvents) => {
  const model = useReactive(dayjs(value || current).toObject());

  const [dayList, setDayList] = useState<number[]>(
    getdayList(value || current)
  );

  const handleChange = (e) => {
    const vals = e.detail.value;

    const y = yearList[vals[0]];
    const m = monthList[vals[1]];

    const days = dayjs([y, m + 1, 1].join("-")).daysInMonth();
    const d = Math.min(dayList[vals[2]], days);

    model.date = d;
    model.years = y;
    model.months = m;

    setDayList(generateList(days, 1));
    onChange?.(dayjs([y, m + 1, d].join("-")).format("YYYY-MM-DD"));
  };

  const yearValue = findIndex(yearList, model.years);
  const monthValue = findIndex(monthList, model.months);
  const dayValue = findIndex(dayList, model.date);

  console.log("value", model, yearValue, monthValue, dayValue);
  return (
    <PickerView
      className="h-full"
      value={[yearValue, monthValue, dayValue]}
      onChange={handleChange}
    >
      <PickerViewColumn>
        {yearList.map((e) => (
          <View key={e} className="h-[100px] text-center">
            {e}年
          </View>
        ))}
      </PickerViewColumn>

      <PickerViewColumn>
        {monthList.map((e) => (
          <View key={e} className="h-[100px] text-center">
            {e + 1}月
          </View>
        ))}
      </PickerViewColumn>

      <PickerViewColumn>
        {dayList.map((e) => (
          <View key={e} className="h-[100px] text-center">
            {e}日
          </View>
        ))}
      </PickerViewColumn>
    </PickerView>
  );
};
